package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-11-12
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {

        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = baseMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getId, id)
                .select(ProductSku::getId, ProductSku::getSkuSpec));
        //封装数据
        HashMap<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(),item.getId());
        });
        return skuSpecValueMap;
    }

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //1.优先从缓存中获取数据
            //1.1 构建业务数据Key 形式：前缀+业务唯一标识
            String dataKey = "product:sku:" + skuId;
            //1.2 查询Redis获取业务数据
            ProductSku productSku = (ProductSku)redisTemplate.opsForValue().get(dataKey);
            //1.3 命中缓存则直接返回
            if (productSku != null) {
                log.info("命中缓存，直接返回，线程ID：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                return productSku;
            }

            //2.尝试获取分布式锁（set k v nx ex 可能获取锁失败）
            //2.1 构建锁key
            String lockKey = "product:sku:lock:" + skuId;
            //2.2 采用UUID作为线程标识
            String lockVal = UUID.randomUUID().toString().replaceAll("-","");
            //2.3 利用Redis提供set nx ex 获取分布式锁
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockVal, 5, TimeUnit.SECONDS);
            if (flag) {
                //3.获取锁成功执行业务,将查询业务数据放入缓存Redis
                log.info("获取锁成功：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                try {
                    productSku  = baseMapper.selectById(skuId);
                    //防止缓存穿透，将null值转换成新对象存入数据库，并且设置较短的过期时间
                    long tll = productSku == null ?1*60:10*60;
                    if(productSku == null){
                        productSku = new ProductSku();
                    }
                    //将查询数据库结果放入缓存
                    redisTemplate.opsForValue().set(dataKey,productSku,tll,TimeUnit.SECONDS);
                    return productSku;
                } finally {
                    //4.业务执行完毕释放锁
                    String scriptText = """
                            if redis.call('get',KEYS[1]) == ARGV[1]
                            then
                                return redis.call('del',KEYS[1])
                            else
                                return 0
                            end
                            """;
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(scriptText);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey),lockVal);
                }
            }else {
                try {
                    //5.获取锁失败则自旋（业务要求必须执行）
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.error("获取锁失败，自旋：{}，线程名称：{}",
                        Thread.currentThread().getId(),
                        Thread.currentThread().getName());
                return this.getProductSku(skuId);
            }
        } catch (Exception e) {
            //兜底处理方案：Redis服务有问题，将业务数据获取自动从数据库获取
            log.error("[商品服务]查询商品信息异常：{}", e);
            return baseMapper.selectById(skuId);
        }
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkuList = baseMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getId, skuIdList)
                .select(ProductSku::getId, ProductSku::getSalePrice));
        List<SkuPriceVo> skuPriceVoList = productSkuList.stream().map(item -> {
            SkuPriceVo skuPriceVo = new SkuPriceVo();
            skuPriceVo.setSkuId(item.getId());
            skuPriceVo.setSalePrice(item.getSalePrice());
            skuPriceVo.setMarketPrice(item.getMarketPrice());
            return skuPriceVo;
        }).collect(Collectors.toList());
        return skuPriceVoList;
    }
}
